#include <jni.h>

static char* key= (char *) "";

char* hexdigest(JNIEnv *env,jbyteArray jba){
    jclass clazz =env->FindClass("java/security/MessageDigest");
    jmethodID mid_static_method = env->GetStaticMethodID(clazz,"getInstance","(Ljava/lang/String;)Ljava/security/MessageDigest;");
    jmethodID update_id = env->GetMethodID(clazz, "update", "([B)V");
    jmethodID digest_id = env->GetMethodID(clazz, "digest", "()[B");
    jobject messageDigest = env->CallStaticObjectMethod(clazz,mid_static_method,env->NewStringUTF("MD5"));
    env->CallVoidMethod(messageDigest, update_id,jba);
    jba = static_cast<jbyteArray>(env->CallObjectMethod(messageDigest, digest_id));
    jbyte* bytes = env->GetByteArrayElements(jba, 0);
    char* hexDigits = (char *) "0123456789abcdef";
    char* arrayOfChar = new char[33]();
    int i = 0, j = 0;
    for (i = 0,j=0;i<16; i++, j++) {
        int k = bytes[i];
        int indtx = (0xF & k >> 4);
        arrayOfChar[j] = hexDigits[indtx];
        arrayOfChar[++j] = hexDigits[(k & 0xF)];
    }
    arrayOfChar[32] = '\0';
    return arrayOfChar;
}

extern "C"
JNIEXPORT void JNICALL
Java_com_rndemo_Environmental_AppData_soInit(JNIEnv *env, jclass type, jobject context) {
    jclass native_class = env->GetObjectClass(context);
    jmethodID pm_id = env->GetMethodID(native_class, "getPackageManager", "()Landroid/content/pm/PackageManager;");
    jmethodID mId = env->GetMethodID(native_class, "getPackageName", "()Ljava/lang/String;");
    jobject pm_obj = env->CallObjectMethod(context, pm_id);//PackageManager
    jstring pkg_str = static_cast<jstring>(env->CallObjectMethod(context, mId));//PackageName


    jclass pm_clazz = env->GetObjectClass(pm_obj);
    jmethodID package_info_id = env->GetMethodID(pm_clazz, "getPackageInfo","(Ljava/lang/String;I)Landroid/content/pm/PackageInfo;");
    jobject pi_obj = env->CallObjectMethod(pm_obj, package_info_id, pkg_str, 64/*PackageManager.GET_SIGNATURES*/);//PackageInfo


    jclass pi_clazz = env->GetObjectClass(pi_obj);
    jfieldID signatures_fieldId = env->GetFieldID(pi_clazz, "signatures", "[Landroid/content/pm/Signature;");
    jobject signatures_obj = env->GetObjectField(pi_obj, signatures_fieldId);//signatures

    jobjectArray signaturesArray = (jobjectArray)signatures_obj;
    jobject signature_obj = env->GetObjectArrayElement(signaturesArray, 0);//第0个元素

    jclass signature_clazz = env->GetObjectClass(signature_obj);
    jmethodID string_id = env->GetMethodID(signature_clazz, "toByteArray", "()[B");
    jbyteArray str = static_cast<jbyteArray>(env->CallObjectMethod(signature_obj, string_id));
    key = hexdigest(env,str);
}



